package com.coldchain.auth.runner;

import com.alibaba.fastjson.JSONObject;
import com.coldchain.auth.configuration.KeyConfiguration;
import com.coldchain.auth.constant.RedisKeyConstant;
import com.coldchain.auth.jwt.AECUtil;
import com.coldchain.auth.module.client.entity.Route;
import com.coldchain.auth.module.client.mapper.RouteMapper;
import com.coldchain.common.constant.RedisKeyConstants;
import com.coldchain.common.redis.RedisUtils;
import com.fangliai.core.util.RsaKeyHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.util.List;
import java.util.Map;

@SuppressWarnings("ALL")
@Configuration
@Order(1)
public class AuthServerRunner implements CommandLineRunner {
    private static final Logger log= LoggerFactory.getLogger(AuthServerRunner.class);

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private KeyConfiguration keyConfiguration;

    @Autowired
    private RouteMapper routeMapper;
    @Autowired
    private AECUtil aecUtil;

    @Autowired
    private RsaKeyHelper rsaKeyHelper;

    @Override
    public void run(String... args) throws Exception {
        boolean flag = false;

        if (redisUtils.getRBucket(RedisKeyConstant.REDIS_USER_PRI_KEY).size()>0&&redisUtils.getRBucket(RedisKeyConstant.REDIS_USER_PUB_KEY).size()>0){
            try {
                keyConfiguration.setUserPriKey(rsaKeyHelper.toBytes(aecUtil.decrypt(redisUtils.getRBucket(RedisKeyConstant.REDIS_USER_PRI_KEY).get().toString())));
                keyConfiguration.setUserPubKey(rsaKeyHelper.toBytes(redisUtils.getRBucket(RedisKeyConstant.REDIS_USER_PUB_KEY).get().toString()));
            }catch (Exception e){
                log.error("初始化用户公钥/密钥异常...",e);
                flag = true;
            }
        }else {
            flag=true;
        }
        if(flag){
            Map<String, byte[]> keyMap = rsaKeyHelper.generateKey(keyConfiguration.getUserSecret());
            keyConfiguration.setUserPriKey(keyMap.get("pri"));
            keyConfiguration.setUserPubKey(keyMap.get("pub"));
            redisUtils.getRBucket(RedisKeyConstant.REDIS_USER_PRI_KEY).set(aecUtil.encrypt(rsaKeyHelper.toHexString(keyMap.get("pri"))));
            redisUtils.getRBucket(RedisKeyConstant.REDIS_USER_PUB_KEY).set(rsaKeyHelper.toHexString(keyMap.get("pub")));
        }
        log.info("完成用户公钥/密钥的初始化...");
        flag = false;

        if (redisUtils.getRBucket(RedisKeyConstant.REDIS_SERVICE_PRI_KEY).size()>0
                &&redisUtils.getRBucket(RedisKeyConstant.REDIS_SERVICE_PUB_KEY).size()>0) {
            try {
                keyConfiguration.setServicePriKey(rsaKeyHelper.toBytes(aecUtil.decrypt(redisUtils.getRBucket(RedisKeyConstant.REDIS_SERVICE_PRI_KEY).get().toString())));
                keyConfiguration.setServicePubKey(rsaKeyHelper.toBytes(redisUtils.getRBucket(RedisKeyConstant.REDIS_SERVICE_PUB_KEY).get().toString()));
            }catch (Exception e){
                log.error("初始化服务公钥/密钥异常...",e);
                flag = true;
            }
        } else {
            flag = true;
        }
        if(flag){
            Map<String, byte[]> keyMap = rsaKeyHelper.generateKey(keyConfiguration.getServiceSecret());
            keyConfiguration.setServicePriKey(keyMap.get("pri"));
            keyConfiguration.setServicePubKey(keyMap.get("pub"));
            redisUtils.getRBucket(RedisKeyConstant.REDIS_SERVICE_PRI_KEY).set(aecUtil.encrypt(rsaKeyHelper.toHexString(keyMap.get("pri"))));
            redisUtils.getRBucket(RedisKeyConstant.REDIS_SERVICE_PUB_KEY).set(rsaKeyHelper.toHexString(keyMap.get("pub")));
        }
        log.info("完成服务公钥/密钥的初始化...");
        List<Route> gatewayRoutes = routeMapper.selectList(null);
        redisUtils.getRBucket(RedisKeyConstants.ZUUL_ROUTE_KEY).set(JSONObject.toJSONString(gatewayRoutes));
        log.info("完成网关路由的更新...");
    }
}
